package com.janyee.buddha.entity

import android.graphics.Canvas
import android.graphics.Paint
import android.text.TextPaint
import android.util.Log
import com.janyee.buddha.util.ReaderUtil
import com.janyee.buddha.view.Painter
import org.w3c.dom.Text
import kotlin.math.max

/**
 * Created by kmlixh on 17/11/27.
 * useage:
 * TextTest
 *
 */

open class LineText(val index: Int, val count: Int, var startIdx: Int, var endIdx: Int) {

    fun length():Int{
        return count
    }


    fun draw(canvas: Canvas, painter: Painter, left: Float, top: Float, text: StringBuilder) {
        var singleWidth = painter.getNormalTextPaint().measureText("测")
        var bt = ""//选中之前的文字
        var ct = ""//选中的文字
        var at = ""//选中之后的文字
        var pos = left//绘图基点
        val baseY = painter.getNormalTextPaint().fontMetrics.descent - painter.getNormalTextPaint().fontMetrics.ascent
        val baseLine = -painter.getNormalTextPaint().fontMetrics.ascent+top
        if (startIdx == -1) {
            bt = text.substring(index, index + count)
        } else {
            bt = text.substring(index, index + startIdx)
            if (endIdx >=0) {
                ct = text.substring(index + startIdx, index + endIdx)
                at = text.substring(index + endIdx, index + count)
            } else {
                ct = text.substring(index + startIdx, index + count)
            }

        }

        if (bt.isNotEmpty()) {
            drawText(canvas,bt, pos, baseLine, painter.getNormalTextPaint())
            pos += bt.length*singleWidth
        }
        if (ct.isNotEmpty()) {
            canvas.drawRect(pos, top, pos + ct.length * singleWidth, baseY + top, painter.getChoosedBackPaint())
            drawText(canvas,ct, pos, baseLine, painter.getChoosedTextPaint())
            pos += ct.length*singleWidth
        }
        if (at.isNotEmpty()) {
            drawText(canvas,at, pos, baseLine, painter.getNormalTextPaint())
        }
    }
    fun drawText(canvas: Canvas,text:String,x:Float,y:Float,paint:Paint){
        canvas.drawText(text, x, y, paint)
    }

    fun choosed(startIdx: Int, endIdx: Int) {
        this.startIdx = startIdx
        this.endIdx = endIdx
    }
}
